<template>
	<xn-form-container
		:title="formData.id ? '编辑模块' : '增加模块'"
		:width="550"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-form-item label="名称" name="name">
				<a-input v-model:value="formData.name" placeholder="请输入名称" allow-clear/>
			</a-form-item>
			<a-form-item label="编码" name="code">
				<a-input v-model:value="formData.code" placeholder="请输入编码" allow-clear/>
			</a-form-item>
			<a-form-item label="账户名称" name="accountName">
				<a-input
					v-model:value="formData.accountName"
					placeholder="请输入账户名称"
					allow-clear
				/>
			</a-form-item>
			<a-form-item label="开户行名称" name="bankName">
				<a-input v-model:value="formData.bankName" placeholder="请输入开户行名称" allow-clear/>
			</a-form-item>
			<a-form-item label="开户行账号" name="bankAccount">
				<a-input v-model:value="formData.bankAccount" placeholder="请输入开户行账号" allow-clear/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button class="xn-mr8" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit">保存</a-button>
		</template>
		<Icon-selector ref="iconSelectorRef" @iconCallBack="iconCallBack"/>
	</xn-form-container>
</template>

<script setup>
import {required} from '@/utils/formRules'
import IconSelector from '@/components/Selector/iconSelector.vue'
import bankApi from "@/api/tjzy/bank/bankApi";
// 默认是关闭状态
const visible = ref(false)
const emit = defineEmits({successful: null})
const formRef = ref()
const iconSelectorRef = ref()
// 表单数据
const formData = ref({})

// 打开抽屉
const onOpen = (record) => {
	visible.value = true
	formData.value = {
		sortCode: 99
	}
	if (record) {
		formData.value = Object.assign({}, record)
	} else {
		formData.value = {
			sortCode: 99,
			color: '#1677FF'
		}
	}
}
// 关闭抽屉
const onClose = () => {
	formRef.value.resetFields()
	visible.value = false
}
// 图标选择器回调
const iconCallBack = (value) => {
	if (value) {
		formRef.value.clearValidate('icon')
	}
	formData.value.icon = value
}

// 默认要校验的
const formRules = {
	name: [required('请输入名称')],
	code: [required('请输入编码')],
	accountName: [required('请输入账户名称')],
	bankName: [required('请输入开户行名称')],
	bankAccount: [required('请输入开户行账号')]
}

// 验证并提交数据
const onSubmit = () => {
	formRef.value
		.validate()
		.then(() => {
			console.log(formData.value)
			if (formData.value.id) {
				bankApi.edit(formData.value).then(() => {
					onClose()
					emit('successful')
				})
			} else {
				bankApi.add(formData.value).then(() => {
					onClose()
					emit('successful')
				})
			}
		})
		.catch(() => {
		})
}

// 调用这个函数将子组件的一些数据和方法暴露出去
defineExpose({
	onOpen
})
</script>
